import { nextTick, ref, unref } from 'vue'

interface Config {
  maxDistanceY: number
  wait: number
}

export const useGlobalLoading = (
  config: Config = {
    maxDistanceY: 110,
    wait: 1000
  }
) => {
  let startY = 0,
    endY = 0,
    distanceY = 0

  const elIcon: HTMLElement | any = ref()

  const initElMount = (el: HTMLElement | any) => {
    elIcon.value = el
  }

  const getInstanceEl = async () => {
    const instance: HTMLElement | any = unref(elIcon.value)
    await nextTick()
    return instance
  }

  const touchStart = (e: TouchEvent) => {
    startY = e.touches[0].clientY
  }

  const elMove = (e: TouchEvent) => {
    endY = e.touches[0].clientY
    distanceY = endY - startY
    if (distanceY > config.maxDistanceY) return
    elIcon.value.style.transform = `translateY(${distanceY}px)`
    elIcon.value.style.transition = 'all .3s'
  }

  const elCancel = (http: <T = any>(params?: T) => Promise<T>) => {
    return new Promise((resovle, reject) => {
      http()
        .then((res) => {
          resovle(res)
        })
        .catch((err) => reject(err))
        .finally(() => {
          setTimeout(() => {
            elIcon.value.style.transform = `translateY(0)`
            elIcon.value.style.transition = 'all .3s'
          }, config.wait)
        })
    })
  }

  return {
    touchStart,
    elMove,
    elCancel,
    initElMount,
    getInstanceEl
  }
}
